<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>照片上传</title>
    <link href="../upload/layui/css/layui.css" rel="stylesheet"/>
<!--    <link rel="stylesheet" href="js/layui/css/layui.css">-->
<!--    <link rel="icon" href="img/logo.png" type="image/x-icon"/>-->
<!--    <link rel="shortcut icon" href="img/logo.png" type="image/x-icon"/>-->
    <style>
		html,body{
			height: 100%;
		}
        .same {
            margin: 0;
            box-sizing: border-box;
            border: 0;
            height: 49px;
            padding-top: 1px;
        }

        .div {
            width: 600px;
            height: 54px;
            border: solid 1px #000000;
        }

        .text {
            width: 80%;
            background-color: white;
        }

        .btn {
            width: 20%;
            background-color: #3588FE;
        }

    </style>



</head>
<body>
<div id="fieldsetBox" style="height: 100%;">
<fieldset  class="layui-elem-field site-demo-button" style="margin: 0;">
    <legend>照片上传</legend>
		<!-- 高28 -->
    <div class="layui-upload" style="padding: 0 10px;">
        <form class="layui-form" action="">
					<!-- 高44 -->
            <div class="layui-form-item" style="margin: 0;">
                <div class="layui-inline">
                    <label class="layui-form-label">人脸组</label>
                    <div class="layui-input-inline" style="width: 200px;">
                        <select id="group" lay-verify="" lay-search>
                            <option value=""></option>
                        </select>
                    </div>

                    <div class="layui-input-inline" style="width: 100px;">
                        <button type="button" class="layui-btn layui-btn-normal" id="testList">选择照片</button>
                    </div>

                    <div class="layui-input-inline" style="width: 100px;">
                        <button type="button" class="layui-btn" id="btnUpload">开始上传</button>
                    </div>

                    <div class="layui-progress layui-progress-big layui-input-inline" lay-filter="demo" lay-showPercent="yes" style="margin-top: 12px; width: 300px;">
                        <div class="layui-progress-bar" lay-percent="0%"></div>
                    </div>
                </div>


            </div>
        </form>

        <!-- <div class="layui-upload-list">
            <table class="layui-table">
                <thead>
                <tr>
                    <th>文件名</th>
                    <th>大小</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="demoList"></tbody>
            </table>
        </div> -->
				<!-- 表格，margin上下各15px -->
        <table id="uploadList" lay-filter="test" style="margin: 0;"></table>
				
    </div>
</fieldset>
</div>

</body>
<script src="../upload/js/lodash.min.js"></script>
<script src="../upload/layui/layui.js" charset="utf-8"></script>
<!--<script src="js/layui/layui.js"></script>-->
<script src="../upload/js/jquery.js"></script>

<script type="text/html" id="bar">

    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</a>

</script>

<script>
    layui.use(['upload', 'layer', 'form', 'table', 'element'], function () {
        var $ = layui.jquery
            , upload = layui.upload,
            layer = layui.layer,
            table = layui.table
            ,element = layui.element;
        element.progress('demo', "0%");
        //设置全局url，用户自己修改
        var url = "http://localhost:8080/fileupload/";
        var dataList = [];
        var DISABLED = 'layui-btn-disabled';
        // var name = "112234张三";
        // console.log(name.substring(0,6));
        // console.log(name.substring(6));

        table.render({
            elem: '#uploadList'
            ,height: $("#fieldsetBox").height()-92
            // ,url: '/demo/table/user/' //数据接口
            ,page: true //开启分页
            ,limit: 50
            ,cols: [[ //表头
                {field: 'fileName', title: '文件名',align:'center', width:400, sort: false, fixed: 'left'}
                ,{field: 'fileSize', title: '文件大小',align:'center', width:200}
                ,{field: 'fileStatus', title: '状态', align:'center',width:200, sort: false}
                ,{field: 'action', title: '操作', align:'center', width:140,toolbar: "#bar"}
            ]],
            data: dataList
        });

//监听事件
        table.on('tool(test)', function(obj){
            console.log(obj);
            // var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'add':

                case 'delete':
                    obj.del(obj);
                    _(files).forEach(function(file,index){
                        delete files[index];
                    });
                    layer.msg('删除成功！');
					shade: 0.7
                    break;
            }
        });

        // 加载组数据
        $.ajax({
            //请求方式
            type : "POST",
            //请求的媒体类型
            contentType: "application/json;charset=UTF-8",
            //请求地址
            // url : "http://localhost:9090/api/test/list/period",
            url : "/face/clustering/group/query",
            //数据，json字符串
            // data : JSON.stringify({
            //     "parent": "00106"
            // }),
            data : JSON.stringify({
                "type": "queryByPage",
                "pageNumber": 1,
                "pageSize": 10000,
                "faceCount": false
            }),
            //请求成功
            success : function(res) {
                $.each(res.rows, function (index, item) {
                    $('#group').append(new Option(item.info,item.groupId));
                });
                layui.form.render("select");
            },
            //请求失败，包含具体的错误信息
            error : function(e){
                console.log(e.status);
                // console.log(e.responseText);
            }
        });		

        $('#btnUpload').on('click', function () {
            element.progress('demo', '0%');

            var groupId = $('#group').val();
            if(_.isEmpty(groupId)) {
                alert("请选择人脸组");
                return;
            }

            if(!dataList || dataList.length === 0) {
                alert("请选择要上传的人脸照片");
                return;
            }

            layer.load(1, {
              icon: 16
              ,shade: 0.01
            });

            var c = 0, total = dataList.length;
            _(dataList).forEach(function(row, index) {

                setTimeout(function () {
                    var reader = new FileReader(); //创建FileReader对象实例reader
                    reader.readAsDataURL(row.fileData); //将图片url转换为base64码
                    reader.onload = function(e){
                        var newUrl = this.result;
                        // loading层
                        // layer.msg("正在上传..."+c+"/"+dataList.length, {
                        //   icon: 16
                        //   ,shade: 0.01
                        // });
                        var baseArr = _.split(newUrl, ',');
                        var allName = _.split(row.fileData.name, '.');  //带有后缀得图片全名
                        var baseName = allName[0];  //取到没有后缀得图片名字

                        $.ajax({
                            //请求方式
                            type : "POST",
                            async: false,
                            //请求的媒体类型
                            contentType: "application/json;charset=UTF-8",
                            url : "/face/clustering/face/create",
                            data : JSON.stringify({
                                "groupId": groupId,
                                "tag": baseName,
                                "img": baseArr[1]
                            }),
                            //请求成功
                            success : function(res) {
                                if (res.info === "success") { //上传成功
                                    c = c + 1;
                                    // row.fileStatus = "上传成功";
                                    // row.action = "";
                                    // table.reload("uploadList" ,{
                                    //     data: dataList
                                    // });
                                    // layer.msg("正在上传..." + c + "/" + total, {
                                    //     icon: 16
                                    //     ,shade: 0.01
                                    // });
                                    console.log(c);
                                    console.log((c/total*100).toFixed(2));
                                    element.progress('demo', (c/total*100).toFixed(0)+'%');
                                    // layer.msg("照片上传成功");
                                    // dataList = [];
                                    // table.reload("uploadList" ,{
                                    //     data: dataList
                                    // });

                                    // delete files[index];
                                    // _(files).forEach(function(file,index){
                                    //         delete files[index];
                                    // });
                                    if (c === dataList.length) {
                                        layer.closeAll('loading');
                                        element.progress('demo', '0%');
                                        dataList = [];
                                        table.reload("uploadList" , {
                                            data: dataList
                                        });

                                    }
                                }
                                // setTimeout(function(){
                                //   // layer.closeAll('loading');
                                //   if (c === dataList.length - 1) {
                                //       dataList = [];
                                //       table.reload("uploadList" , {
                                //           data: dataList
                                //       });
                                //   }
                                // }, 500);
                            },
                            //请求失败，包含具体的错误信息
                            error : function(e){
                                // alert("---------" + e);
                                // console.log(e);
                            }
                        });

                        // if (res.info === "success") { //上传成功
                        //     c = c + 1;
                        //     row.fileStatus = "上传成功";
                        //     row.action = "";
                        //     table.reload("uploadList" ,{
                        //         data: dataList
                        //     });
                        //
                        //     if( c === dataList.length - 1) {
                        //         layer.msg("上传完毕.", {
                        //             icon: 16
                        //             ,shade: 0.01
                        //         });
                        //     }
                        //     // else {
                        //     //     layer.msg("正在上传..." + c + "/" + dataList.length, {
                        //     //         icon: 16
                        //     //         , shade: 0.01
                        //     //     });
                        //     // }
                        //     // dataList = [];
                        //     // table.reload("uploadList" ,{
                        //     //     data: dataList
                        //     // });
                        //
                        //     // delete files[index];
                        //     // _(files).forEach(function(file,index){
                        //     //         delete files[index];
                        //     // });
                        // }
                    };
                }, 2000);

            });
        });

        var files = [];
        var upFiles = [];    
        //多文件列表示例
        var demoListView = $('#demoList');
        var uploadListIns = upload.render({
            elem: '#testList'
            // , url: url+'upload'
            , accept: 'images'
            , acceptMime: 'images/*'
            , exts: 'jpg|png|gif|bmp|jpeg'
            , multiple: true
            , number: 0
            , size: 800
            , auto: false
            // , bindAction: '#testListAction'        
            , choose: function (obj) {
                
                files = upFiles = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                dataList = [];
                // console.log(files);
                
                _(files).forEach(function(file,index){
                    var size = 0;
                     size = (file.size / 1014).toFixed(1);
                     // console.log(size);
                     
                    if (size > 800) {
                        layer.msg("照片不能大于800kb");
                        delete files[index];
                        return
                    } else {
                        dataList.push({fileName: file.name, fileSize: (file.size / 1014).toFixed(1) + 'kb', fileStatus: "正在上传", fileData: file});  
                    }
                });
                //var files = upload.pushFile();
                
                // console.log(dataList);
                dataList = _.uniqBy(dataList,'fileName');
                // console.log(dataList);
                table.reload("uploadList" ,{
                        data: dataList
                });
                //读取本地文件
                // obj.preview(function (index, file, result) {
                //     console.log(file);
                    
                //     var tr = $(['<tr id="upload-' + index + '">'
                //         , '<td>' + file.name + '</td>'
                //         , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                //         , '<td>等待上传</td>'
                //         , '<td>'
                //         , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                //         , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                //         , '</td>'

                //         , '</tr>'].join(''));

                //     //单个重传
                //     tr.find('.demo-reload').on('click', function () {
                //         obj.upload(index, file);
                //     });

                //     //删除
                //     tr.find('.demo-delete').on('click', function () {
                //         delete files[index]; //删除对应的文件
                //         delete upFiles[index];
                //         tr.remove();
                //         uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                //     });
                //     console.log(tr);
                    
                //     demoListView.append(tr);
                    
                // });

            }
            // , done: function (res, index, upload) {
            //     console.log("成功");
                
            //     if (res.code == 200) { //上传成功
            //         var tr = newDataList.find('tr#upload-' + index)
            //             , tds = tr.children();
            //         tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
            //         tds.eq(3).html('<span>' + "" + '</span>'); //清空操作

            //         return delete this.files[index]; //删除文件队列已经上传成功的文件
            //         return delete upFiles[index]; 
                    
            //     }

            //     if (res.code == 201) { //秒传成功
            //         var tr = newDataList.find('tr#upload-' + index)
            //             , tds = tr.children();
            //         tds.eq(2).html('<span style="color: #4e77b8;">秒传成功</span>');
            //         tds.eq(3).html('<span>' + res.data + '</span>'); //清空操作

            //         return delete this.files[index]; //删除文件队列已经上传成功的文件
            //         return delete upFiles[index]; 
            //     }
                
            //     this.error(index, upload);
            // }
            // , error: function (index, upload) {
            //     var tr = newDataList.find('tr#upload-' + index)
            //         , tds = tr.children();
            //     tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            //     tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
            // }
        });

    });

</script>
</html>